package edu.nepu.flink.api.state;

import edu.nepu.flink.api.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.*;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Map;

/**
 * @Date 2024/3/2 10:42
 * @Created by chenshuaijun
 */
public class StateTTLDemo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> source = env.socketTextStream("hadoop102", 9999)
                .flatMap(new FlatMapFunction<String, WaterSensor>() {
                    @Override
                    public void flatMap(String value, Collector<WaterSensor> out) throws Exception {
                        try {
                            String[] split = value.split(",");
                            if (split.length == 3) {
                                out.collect(new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2])));
                            }
                        } catch (Exception e){
                            // 如果因为数据输入错误，产生的异常直接忽略掉
                        }
                    }
                }).assignTimestampsAndWatermarks(WatermarkStrategy.forMonotonousTimestamps()); // 采用处理时间方便演示
        /**
         * TODO 状态的生存时间
         *  我们存储在状态中的数据默认是不清理的，这样时间长了，会占用大量的存储空间，影响checkpoint的时间，所以需要定期的清理
         *  可以通过设置TTL来清理过期的状态
         */
        source.keyBy(WaterSensor::getId).process(new KeyedProcessFunction<String, WaterSensor, String>() {
            ValueState<Integer> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                // 状态的初始化必须要再在Open方法中进行，否者会报错误
                ValueStateDescriptor<Integer> stateDescriptor = new ValueStateDescriptor<>("value-state", Types.INT);
                StateTtlConfig config = StateTtlConfig.newBuilder(Time.seconds(10)) // 设置状态超时时间
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .setStateVisibility(StateTtlConfig
                                .StateVisibility.NeverReturnExpired).build();
                stateDescriptor.enableTimeToLive(config);
                valueState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public void processElement(WaterSensor value, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                Integer pre = valueState.value();
                valueState.update(value.vc);
                out.collect("key："+ctx.getCurrentKey()+"当前的vc值为 "+value.vc+" 之前的为vc值为："+pre);
            }
        }).print();

        env.execute();
    }
}
